import { sendPacket } from "./net.js";

export class EventPacket {
    constructor(direction, scaleX, state, x, y) {
        // 这个不是指角色方向，是指client的IO行为
        this.direction = direction;
        this.scaleX = scaleX;
        this.state = state;
        this.x = x;
        this.y = y;
    }
}


export class PlayerMove {
    constructor() {
        this.space = 500;
        this.lock = false;
        this.EventPackets = {
            type: 'move',
            packets: []
        };

        this.frameSpeed = 20; // 20ms/
        this.now = 0;
    }

    // up() {
    //     this.lock = false;        
    // }

    // off() {
    //     this.lock = true;
    //     this.now = 0;
    // }

    /**
     * 
     * @param {Object} playerData - 没有改变就为null
     */
    update(playerData) {
        if (this.lock) return;

        if (playerData) {
            const { x, y, scaleX, state, direction } = playerData;    
            this.addPacket(direction, scaleX, state, x, y);
        }

        if (this.now === this.space) {
            this.now = 0;
            // 发送包
            if (this.EventPackets.packets.length !== 0) {
                this.send();
            }
        }
        this.now += this.frameSpeed;        
    }

    addPacket(direction, scaleX, state, x ,y) {
        const packet = new EventPacket(direction, scaleX, state, x, y);
        this.EventPackets.packets.push(packet);
    }

    send() {
        sendPacket(JSON.stringify(this.EventPackets));
        this.clearPacket();
    }

    clearPacket() {
        this.EventPackets.packets.length = 0;
    }
}

const playerMove = new PlayerMove();

export default playerMove;